package com.taotao.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.taotao.mapper.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.enums.OperateType;
import com.taotao.common.enums.OrderStatus;
import com.taotao.common.enums.ServiceStatus;
import com.taotao.common.enums.TemplateDesc;
import com.taotao.common.pojo.BaseResult;
import com.taotao.common.utils.Constants;
import com.taotao.common.utils.DateUtil;
import com.taotao.mapperCust.EyGoodsMapperCust;
import com.taotao.pojo.EyAddress;
import com.taotao.pojo.EyMember;
import com.taotao.pojo.EyOrder;
import com.taotao.pojo.EyOrderExample;
import com.taotao.pojo.EyPicture;
import com.taotao.pojo.EyPictureExample;
import com.taotao.pojo.EyService;
import com.taotao.service.MessageInfoService;
import com.taotao.service.OperateLogService;
import com.taotao.service.OrderService;
import com.taotao.service.ParamService;
import com.taotao.service.PictureService;
import com.taotao.service.ServiceService;
import com.taotao.service.WechatService;

@Service
public class ServiceServiceImpl implements ServiceService {

	@Autowired
	EyServiceMapper eyServiceMapper;
	@Autowired
	EyAddressMapper eyAddressMapper;
	@Autowired
	EyReportMapper eyReportMapper;
	@Autowired
	EyViewHistoryMapper eyViewHistoryMapper;
	@Autowired
	EyGoodsMapperCust eyGoodsMapperCust;
	@Autowired
	EyCollectMapper eyCollectMapper;
	@Autowired
	EyCategoryMapper eyCategoryMapper;
	@Autowired
	EyMemberMapper eyMemberMapper;
	@Autowired
	EyOrderMapper eyOrderMapper;
	@Autowired
	EyPictureMapper eyPictureMapper;
	@Autowired
	PictureService pictureService;
	@Autowired
	WechatService wechatService;
	@Autowired
	OperateLogService operateLogService;
	@Autowired
	EySessionInfoMapper eySessionInfoMapper;
	@Autowired
	MessageInfoService messageInfoService;
	@Autowired
	OrderService orderService;
	@Autowired
	ParamService paramService;
	
	BaseResult baseResult = new BaseResult();


	@Override
	public Map<String, Object> serviceAddOrUpdate(Map<String, String> map) {
		try {
			String serviceId=map.get("serviceId");
			String memberId=map.get("memberId");
			String details = map.get("details");
			String serviceName = map.get("serviceName");
			String serviceType = map.get("serviceType");
			String serviceDate = map.get("serviceDate");
			String serviceTime = map.get("serviceTime");
			String serviceWeek = map.get("serviceWeek");
			String addressId = map.get("addressId");
			String addressId2 = map.get("addressId2");
			String wechat = map.get("wechat");
			String mobile = map.get("mobile");
			String price=map.get("price");
			String floor=map.get("floor");
			String floor2=map.get("floor2");
			String duration=map.get("duration");
			String cleanMode=map.get("cleanMode");
			String centerData = map.get("centerData");
			String centerData2 = map.get("centerData2");
//			String outTradeNo=map.get("outTradeNo");

			if(StringUtils.isNotBlank(details) && !wechatService.msgCheck(details)){
				return baseResult.getErrorMap("The details field is risky");
			}

			EyMember member = eyMemberMapper.selectByPrimaryKey(Integer.parseInt(memberId));
			if(member==null){
				return baseResult.getErrorMap("会员编号不存在,memberId:"+memberId);
			}

			EyService service=new EyService();
			service.setDetails(details);
			service.setServiceName(serviceName);
			service.setServiceType(serviceType);
			service.setServiceDate(serviceDate);
			service.setServiceTime(serviceTime);
			service.setServiceWeek(serviceWeek);
			if(StringUtils.isNotBlank(addressId)){
				service.setAddressId(Integer.parseInt(addressId));
			}
			if(StringUtils.isNotBlank(addressId2)){
				service.setAddressId2(Integer.parseInt(addressId2));
			}
			service.setWechat(wechat);
			service.setMobile(mobile);
			service.setPrice(price);
			service.setFloor(floor);
			service.setFloor2(floor2);
			service.setDuration(duration);
			service.setCleanMode(cleanMode);
			service.setCenterdata(centerData);
			service.setCenterdata2(centerData2);

			service.setStatus(ServiceStatus.serviceStatus_1.getCode()); //未处理

			service.setUpdateTime(DateUtil.getDateAndTime());
			if(StringUtils.isNotBlank(serviceId)){ //更新操作
				service.setId(Integer.parseInt(serviceId));
				eyServiceMapper.updateByPrimaryKeySelective(service);
				operateLogService.insert(Integer.parseInt(memberId), Integer.parseInt(serviceId),null,"修改service成功",OperateType.operateType_9.getCode(),"");
			}else{//新增操作
				service.setMemberId(Integer.parseInt(memberId)); //修改是不用赋值，也有可能是管理员修改，原始的memberId不修改
				service.setCreateTime(DateUtil.getDateAndTime());
				eyServiceMapper.insert(service);
				member.setServiceNum(member.getServiceNum()+1); //发布的服务数量加1
				member.setUpdateTime(DateUtil.getDateAndTime());
				eyMemberMapper.updateByPrimaryKeySelective(member);
				serviceId=String.valueOf(service.getId());
				String sender=paramService.getParam("admin_member_id");
				String content=paramService.getParam("default_msg");
				String receiver=memberId;
				String modeType=Constants.service;
				String msgType=Constants.num_1;
				String sessionKey="";
				Boolean onLine=true;
				Map<String, Object> returnMap = messageInfoService.processMessage(sender, receiver, content, modeType, msgType, serviceName, serviceId, onLine, sessionKey,"");//处理消息
				Map<String, String> data = (Map<String, String>) returnMap.get("data");
				sessionKey = data.get("sessionKey");
				String messageId = data.get("messageId");
				//管理员消息提醒
				HashMap<String,String> m=new HashMap<String,String>();
				m.put("sender", receiver);
				m.put("receiver",sender);
				m.put("sessionKey",sessionKey);
				m.put("messageId", messageId);
				m.put("content", "Receive a message");
				m.put("templateId", TemplateDesc.Template_1.getCode());  //客户咨询提醒
				wechatService.sendMsg(m);
				operateLogService.insert(Integer.parseInt(memberId), service.getId(),null,"发布service成功",OperateType.operateType_8.getCode(),"");
			}

			Map<String,String> returnMap2=new HashMap<>();
			returnMap2.put("serviceId", serviceId);
			return baseResult.getSuccMap(returnMap2);
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("网络繁忙，请稍后再试");
		}
	}


	@Override
	public Map<String, Object> getServiceList(Map<String, String> map) {
		try {
			String memberId=map.get("memberId");
			
			EyMember member = eyMemberMapper.selectByPrimaryKey(Integer.parseInt(memberId));
			if(member==null){
				return baseResult.getErrorMap("会员编号不存在,memberId:"+memberId);
			} 
			
			if(Constants.num_1.equals(member.getIsAdmin())){ //管理员查询所有
				map.put("memberId", "");
			}
			
			String pageNum =  map.get("pageNum");
			String pageSize = map.get("pageSize");
			Integer num=StringUtils.isBlank(pageNum)?Constants.pageNum:Integer.parseInt(pageNum);
			Integer size=StringUtils.isBlank(pageSize)?Constants.pageSize:Integer.parseInt(pageSize);
			
			PageHelper.startPage(num,size);
			List<Map> serviceList= eyGoodsMapperCust.getServiceList(map);
			
			for (Map m:serviceList) {
				m.put("createTime", DateUtil.getDateTimeFormatStr3(m.get("createTime").toString()));
				m.put("updateTime", DateUtil.getDateTimeFormatStr3(m.get("updateTime").toString()));
			}
			
			PageInfo<Map> pageInfo = new PageInfo<>(serviceList);
	  		return baseResult.getSuccMap(pageInfo);
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("网络繁忙，请稍后再试");
		}
	}
	
	
	@Override
	public Map<String, Object> getServiceInfo(Map<String, String> map) {
		try {
			String serviceId=map.get("serviceId");
			String orderId=map.get("orderId");
//			String memberId=map.get("memberId");
			EyService service = eyServiceMapper.selectByPrimaryKey(Integer.parseInt(serviceId));
			
			service.setCreateTime(DateUtil.getDateTimeFormatStr(service.getCreateTime()));
			service.setUpdateTime(DateUtil.getDateTimeFormatStr(service.getUpdateTime()));
			
			Integer addressId = service.getAddressId();
			EyAddress address=null;
			if(addressId!=null){
				address = eyAddressMapper.selectByPrimaryKey(addressId);
			}
			Integer addressId2=service.getAddressId2();
			EyAddress address2=null;
			if(addressId2!=null){
				address2 = eyAddressMapper.selectByPrimaryKey(addressId2);
			}
			
			
			Map<String,Object> returnMap=new HashMap<String,Object>();
			EyPictureExample example = new EyPictureExample();
			com.taotao.pojo.EyPictureExample.Criteria criteria = example.createCriteria();
			criteria.andServiceIdEqualTo(Integer.parseInt(serviceId));
			criteria.andStatusNotEqualTo(Constants.num_100);
			example.setOrderByClause(" image_index asc ");
			List<EyPicture> listPic = eyPictureMapper.selectByExample(example);

			String tencentCosEnable=paramService.getParam(Constants.tencent_cos_enable);
			List<String> listPis2=new ArrayList<>();
			for(EyPicture p:listPic){
				String imageUrl = p.getImageUrl();
				if(Constants.false_string.equals(tencentCosEnable)) {
					imageUrl=pictureService.changeDomain(imageUrl);
				}
				listPis2.add(imageUrl);
			}
			
			EyMember member = eyMemberMapper.selectByPrimaryKey(service.getMemberId());
			//如果设置了自己的头像，则使用自己的头像，
			if(StringUtils.isNotBlank(member.getImageUrl())){
				member.setAvatarUrl(member.getImageUrl());
			}
			EyOrderExample exampleOrder = new EyOrderExample();
			com.taotao.pojo.EyOrderExample.Criteria criteriaOrder = exampleOrder.createCriteria();
			if(StringUtils.isNotBlank(orderId)){
				criteriaOrder.andIdEqualTo(Integer.parseInt(orderId));
			}else{
				criteriaOrder.andServiceIdEqualTo(Integer.parseInt(serviceId));
			}
			List<EyOrder> listOrder = eyOrderMapper.selectByExample(exampleOrder);
			String showRefund="false";
			EyOrder orderInfo=new EyOrder();
			if(listOrder!=null && listOrder.size()>0){
				orderInfo = listOrder.get(0);
				String status = orderInfo.getStatus();
				orderInfo.setStatusDesc(OrderStatus.getValue(status));

				String createTime=orderInfo.getCreateTime();
				String beforeData=DateUtil.getDateAndTime(-15);
				if(createTime.compareTo(beforeData)>0){
					showRefund="true";
				}

				//价格显示支付的价格，有可能同一个服务多次付款，多个订单，显示的是该笔订单的价格，和是否支付
				service.setPrice(orderInfo.getPriceTotal());

			}else{
				orderInfo.setStatusDesc(Constants.notPay);
			}

			returnMap.put("showRefund",showRefund);
			returnMap.put("orderInfo",orderInfo);
			returnMap.put("member", member);
			returnMap.put("address", address);
			returnMap.put("address2", address2);
			returnMap.put("service", service);
			returnMap.put("picList", listPis2);
			return baseResult.getSuccMap(returnMap);
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("网络繁忙，请稍后再试");
		}
	}
	


	
	@Override
	public Map<String, Object> modifyServiceStatus(Map<String, String> map) {
		try {
			String status=map.get("status");
			String serviceId=map.get("serviceId");
			EyService service = eyServiceMapper.selectByPrimaryKey(Integer.parseInt(serviceId));
			if(service==null){
				return baseResult.getErrorMap("serviceId不存在,serviceId:"+serviceId);
			}
			
			String value = ServiceStatus.getValue(status);
			if(StringUtils.isBlank(value)){
				return baseResult.getErrorMap("修改的状态不合法");
			}
			
			EyService s=new EyService();
			s.setId(Integer.parseInt(serviceId));
			s.setStatus(status);
			s.setUpdateTime(DateUtil.getDateAndTime());
			eyServiceMapper.updateByPrimaryKeySelective(s);
			
			operateLogService.insert(service.getMemberId(), Integer.parseInt(serviceId),null,"修改service状态，状态改为："+status,OperateType.operateType_17.getCode(),""); 
			
			return baseResult.getSuccMap();
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("网络繁忙，请稍后再试");
		}
	}


	@Override
	public Map<String, Object> deleteService(Map<String, String> map) {
		try {
			String serviceId=map.get("serviceId");
			EyService service = eyServiceMapper.selectByPrimaryKey(Integer.parseInt(serviceId));
			if(service==null){
				return baseResult.getErrorMap("serviceId不存在,serviceId:"+serviceId);
			}
			
			service.setStatus(ServiceStatus.serviceStatus_100.getCode());
			eyServiceMapper.updateByPrimaryKey(service);
			
			operateLogService.insert(service.getMemberId(), Integer.parseInt(serviceId),null,"删除service成功",OperateType.operateType_10.getCode(),""); 
			
			return baseResult.getSuccMap();
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorMap("网络繁忙，请稍后再试");
		}
	}		

	
}
